﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using TransControlSystem.Dao;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel.Common
{
    public class LogViewModel : ViewModelBase
    {
        //开始
        private int start = 0;
        //每页数量
        private int itemCount = 10;
        //默认排序字段
        private string sortColumn = "OperTime";
        private bool ascending = false;
        //总数量
        private int totalItems = 0;

        /// <summary>
        /// 开始
        /// </summary>
        public int Start { get { return start + 1; } }

        /// <summary>
        /// 最后一页
        /// </summary>
        public int End { get { return start + itemCount < totalItems ? start + itemCount : totalItems; } }

        /// <summary>
        /// 总数据量
        /// </summary>
        public int TotalItems { get { return totalItems; } }
        /// <summary>
        /// 首页命令
        /// </summary>
        public DelegateCommand FirstCommand { get; set; }
        /// <summary>
        /// 上一页命令
        /// </summary>
        public DelegateCommand PreviousCommand { get; set; }
        /// <summary>
        /// 下一页命令
        /// </summary>
        public DelegateCommand NextCommand { get; set; }
        /// <summary>
        /// 最后一页命令
        /// </summary>
        public DelegateCommand LastCommand { get; set; }

        /// <summary>
        /// 搜索命令
        /// </summary>
        public DelegateCommand SearchCommand { get; set; }

        /// <summary>
        /// 隐藏窗体命令
        /// </summary>
        public DelegateCommand HideLogWindowCommand { get; set; }

        /// <summary>
        /// UI日志列表
        /// </summary>
        private ObservableCollection<Log> _Logs;
        /// <summary>
        /// UI任务列表
        /// </summary>
        public ObservableCollection<Log> Logs
        {
            get { return _Logs; }
            set
            {
                _Logs = value;
                RaisePropertyChanged("Logs");
            }
        }
        /// <summary>
        /// 搜索使用用户
        /// </summary>
        private string _UserName;
        /// <summary>
        /// 搜索使用用户
        /// </summary>
        public string UserName
        {
            get { return _UserName; }
            set
            {
                _UserName = value;
                RaisePropertyChanged("UserName");
            }
        }
        /// <summary>
        /// 搜索使用操作内容
        /// </summary>
        private string _OperContent;
        /// <summary>
        /// 搜索使用操作内容 
        /// </summary>
        public string OperContent
        {
            get { return _OperContent; }
            set
            {
                _OperContent = value;
                RaisePropertyChanged("OperContent");
            }
        }

        /// <summary>
        /// 结束时间搜索使用的开始时间范围
        /// </summary>
        private string _StartTime;
        /// <summary>
        /// 结束时间搜索使用的开始时间范围
        /// </summary>
        public string StartTime
        {
            get { return _StartTime; }
            set
            {
                _StartTime = value;
                RaisePropertyChanged("StartTime");
            }
        }

        /// <summary>
        /// 结束时间搜索使用的结束时间范围
        /// </summary>
        private string _EndTime;
        /// <summary>
        /// 结束时间搜索使用的结束时间范围
        /// </summary>
        public string EndTime
        {
            get { return _EndTime; }
            set
            {
                _EndTime = value;
                RaisePropertyChanged("EndTime");
            }
        }

        /// <summary>
        /// 数据库中任务数量
        /// </summary>
        private ObservableCollection<Log> DataLogs = new ObservableCollection<Log>();
        /// <summary>
        /// 构造函数
        /// </summary>
        public LogViewModel()
        {
            //获取所有任务列表平
            string WhereSql = " WHERE 1 = 1";
            if (UserName != null && UserName.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(UserName))
                {
                    WindowManager.ShowWarning("警告", "用户不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereSql += " AND ( l.UserName LIKE '%" + UserName + "%' OR u.Account LIKE '%" + UserName + "%')";
            }
            if (OperContent != null && OperContent.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(OperContent))
                {
                    WindowManager.ShowWarning("警告", "操作内容不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereSql += " AND ( l.OperName LIKE '%" + OperContent + "%' OR l.OperContent LIKE '%" + OperContent + "%')";
            }

            if (StartTime != null)
            {
                WhereSql += " AND OperTime >= CONVERT(datetime2(7),'" + StartTime + "')";
            }
            if (EndTime != null)
            {
                WhereSql += " AND OperTime <= CONVERT(datetime2(7),'" + EndTime + "')";
            }
            string Sql = "SELECT l.*,u.Account FROM Log l LEFT JOIN [User] u ON l.UserName = u.UserName" + WhereSql + " ORDER BY OperTime Desc"; ;
            List<Log> LogList = DapperTools.Query<Log>(Sql);
            DataLogs.Clear();
            LogList.ForEach(obj =>
            {
                DataLogs.Add(obj);
            });
            //初始化首页命令
            FirstCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(FirstFuncationHandler)
            };
            //初始化上一页命令
            PreviousCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(PreviousFuncationHandler)
            };
            //初始化下一页命令
            NextCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(NextFuncationHandler)
            };
            //初始化最后一页命令
            LastCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(LastFuncationHandler)
            };
            //初始化搜索命令
            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };
            //初始化隐藏窗体命令
            HideLogWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideLogWindowHandler)
            };
            loadTaskInfos();
        }

        /// <summary>
        /// 搜索处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void SearchHandler(object obj)
        {
            //获取所有任务列表
            string WhereSql = " WHERE 1 = 1";
            if (UserName != null && UserName.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(UserName))
                {
                    WindowManager.ShowWarning("警告", "用户不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereSql += " AND ( l.UserName LIKE '%" + UserName + "%' OR u.Account LIKE '%" + UserName + "%')";
            }
            if (OperContent != null && OperContent.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(OperContent))
                {
                    WindowManager.ShowWarning("警告", "操作内容不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereSql += " AND ( l.OperName LIKE '%" + OperContent + "%' OR l.OperContent LIKE '%" + OperContent + "%')";
            }

            if (StartTime != null)
            {
                WhereSql += " AND OperTime >= CONVERT(datetime2(7),'" + StartTime + "')";
            }
            if (EndTime != null)
            {
                WhereSql += " AND OperTime <= CONVERT(datetime2(7),'" + EndTime + "')";
            }
            string Sql = "SELECT l.*,u.Account FROM Log l LEFT JOIN [User] u ON l.UserName = u.UserName" + WhereSql + " ORDER BY OperTime Desc";
            List<Log> LogList = DapperTools.Query<Log>(Sql);
            DataLogs.Clear();
            LogList.ForEach(item =>
            {
                DataLogs.Add(item);
            });
            loadTaskInfos();
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="propertyName">Name of the changed property.</param>
        private void loadTaskInfos()
        {
            Logs = GetTaskInfos(start, itemCount, sortColumn, ascending, out totalItems);
        }

        /// <summary>
        /// 隐藏任务查询窗体处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void HideLogWindowHandler(object obj)
        {
            UserName = null;
            OperContent = null;
            StartTime = null;
            EndTime = null;
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideLogWindow"));
        }
        /// <summary>
        /// 首页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void FirstFuncationHandler(object obj)
        {
            if (Start - itemCount >= 0)
            {
                start = 0;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }
        /// <summary>
        /// 前一页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void PreviousFuncationHandler(object obj)
        {
            if (start - itemCount >= 0)
            {
                start -= itemCount;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }
        /// <summary>
        /// 下一页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void NextFuncationHandler(object obj)
        {
            if (start + itemCount < totalItems)
            {
                start += itemCount;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }
        /// <summary>
        /// 最后一页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void LastFuncationHandler(object obj)
        {
            if (start + itemCount < totalItems)
            {
                start = (totalItems / itemCount - 1) * itemCount;
                start += totalItems % itemCount == 0 ? 0 : itemCount;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }

        /// <summary>
        ///  获取分页数据
        /// </summary>
        /// <param name="start">从零开始的索引，用于确定展示的列表的起始。</param>
        /// <param name="itemCount">每页显示数量</param>
        /// <param name="sortColumn">排序字段</param>
        /// <param name="ascending">排序方式</param>
        /// <param name="totalItems">总数量</param>
        /// <returns>结果列表</returns>
        public ObservableCollection<Log> GetTaskInfos(int start, int itemCount, string sortColumn, bool ascending, out int totalItems)
        {
            totalItems = DataLogs.Count;
            ObservableCollection<Log> sortedTaskInfos = new ObservableCollection<Log>();
            switch (sortColumn)
            {
                case ("Id"):
                    sortedTaskInfos = new ObservableCollection<Log>
                    (
                        from p in DataLogs
                        orderby p.Id
                        select p
                    );
                    break;
                case ("OperTime"):
                    sortedTaskInfos = new ObservableCollection<Log>
                    (
                        from p in DataLogs
                        orderby p.OperTime
                        select p
                    );
                    break;
            }
            sortedTaskInfos = ascending ? sortedTaskInfos : new ObservableCollection<Log>(sortedTaskInfos.Reverse());
            ObservableCollection<Log> filteredTaskInfos = new ObservableCollection<Log>();
            for (int i = start; i < start + itemCount && i < totalItems; i++)
            {
                sortedTaskInfos[i].DataOrderNo = i + 1;
                filteredTaskInfos.Add(sortedTaskInfos[i]);
            }
            return filteredTaskInfos;
        }

    }
}
